package com.xquant.common.engine.xPP;

import com.xquant.common.engine.xPP.cxf.XQuantPPService;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;

/**
 * @Auther: B946
 * @Date: 02/03/2020 14:30
 * @Description:
 */
@WebFilter(filterName = "XQuantPPFilter", urlPatterns = {"/webServices/xQuantPP/*"})
public class XQuantPPFilter implements Filter {

    private static Logger logger = LoggerFactory.getLogger(XQuantPPFilter.class);

    @Autowired
    private XQuantPPService xQuantPPService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("初始化了");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        logger.info("过滤了");

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        try {
            Map pp = xQuantPPService.getPPItem();
            HttpPost httpPost = new HttpPost(MapUtils.getString(pp, "address"));
            //构造新的请求数据流
            InputStreamEntity entity = new InputStreamEntity(request.getInputStream());
            httpPost.setEntity(entity);
            //复制请求参数
            for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements(); ) {
                String name = e.nextElement().toString();
                //注意这里不要设置，发送请求会抛异常
                if ("Content-Length".equalsIgnoreCase(name)) {
                    continue;
                }
                httpPost.setHeader(name, request.getHeader(name));
            }
            //host参数需要覆盖，设置为webservice服务提供这的主机
            httpPost.setHeader("host", MapUtils.getString(pp, "host"));
            //提交soap请求
            HttpResponse httpResponse = HttpClientUtil.getHttpClient().execute(httpPost);
            //复制soap相应的消息头
            for (Header h : httpResponse.getAllHeaders()) {
                logger.info("设置response的header：" + h.getName() + "----");
                logger.info("设置response的value：" + h.getValue());
                response.setHeader(h.getName(), h.getValue());
            }
            //讲soap的返回流复制到filter的输出流
            IOUtils.copy(httpResponse.getEntity().getContent(), response.getOutputStream());
            response.getOutputStream().flush();
//            chain.doFilter(req,resp);
//            return;
        } catch (Exception e) {
            response.setContentType("text/xml;charset=UTF-8");
            String result = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<soap:Body><soap:Fault><faultcode>" + "9999" + "</faultcode>" + "<faultstring>" + "失败:" + e.getMessage() + "</faultstring></soap:Fault></soap:Body></soap:Envelope>";
            response.getWriter().print(result);
        }

    }

    @Override
    public void destroy() {

    }
}
